package cn.base.demo1;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TankGame extends JFrame implements ActionListener {
    // private Tank tank1, tank2;
    private int x1, y1, x2, y2;
    private Timer timer;
    private int delay = 500; // 控制游戏速度的延迟时间
    private int direction1 = 0, direction2 = 0; // 控制坦克的移动方向

    public TankGame() {
        setTitle("坦克大战");
        setSize(600, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setFocusable(true);
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();
                if (keyCode == KeyEvent.VK_LEFT) {
                    direction1 = -1;
                } else if (keyCode == KeyEvent.VK_RIGHT) {
                    direction1 = 1;
                } else if (keyCode == KeyEvent.VK_UP) {
                    direction2 = -1;
                } else if (keyCode == KeyEvent.VK_DOWN) {
                    direction2 = 1;
                }
            }
        });
        setVisible(true);
        init();
    }

    private void init() {
        // tank1 = new Tank(50, 50, 30, 30, "redTank.png", this);
        // tank2 = new Tank(480, 50, 30, 30, "blueTank.png", this);
        // timer = new Timer(delay, this);
        // timer.start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        x1 += direction1 * 5;
        y1 += direction1 * 5;
        x2 += direction2 * 5;
        y2 += direction2 * 5;
        repaint(); // 重新绘制界面
    }

    // @Override
    public void keyReleased(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if (keyCode == KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_DOWN) {
            direction1 = direction2 = 0; // 松开键盘后，停止坦克的移动
        }
    }

    // @Override
    public void keyTyped(KeyEvent e) {
    } // 省略掉键盘输入事件处理代码

    // @Override
    protected void paintComponent(Graphics g) {
        // super.paintComponent(g); // 在界面中绘制坦克和子弹的图片
        // g.drawImage(tank1.getImage(), x1, y1, this); // 在界面上绘制红色坦克图片
        // g.drawImage(tank2.getImage(), x2, y2, this); // 在界面上绘制蓝色坦克图片
        // tank1.shoot(); // 让红色坦克发射子弹，子弹的移动由子弹类自行处理
        // tank2.shoot(); // 让蓝色坦克发射子弹，子弹的移动由子弹类自行处理
    }
}